﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormSocketServer
{
    public partial class Form1 : Form
    {
        private Socket sSocket;

        private Hashtable hashtable = new Hashtable();

        private object sessionLock = new object();


        public Form1()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            int port = 6000;
            string host = "127.0.0.1";
            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);
            sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sSocket.Bind(ipe);
            sSocket.Listen(0);
            AddMessageBox("监听已经打开，请等待");
            Accept();
        }

        /// <summary>
        /// 接受请求
        /// </summary>
        private void Accept()
        {
            Socket serverSocket;
            Task.Run(() => { serverSocket = sSocket.Accept();
                AddMessageBoxAync(serverSocket.RemoteEndPoint.ToString()+" 连接已经建立");
                //保存会话信息
                //Session session = new Session(serverSocket);
                //hashtable.Add(session.IP, session.ClientSocket);

                //首次连接发送问候数据
                string sendStr = "send to client :hello";
                byte[] sendByte = Encoding.ASCII.GetBytes(sendStr);
                serverSocket.Send(sendByte, sendByte.Length, 0);
                return serverSocket;
            }).ContinueWith((x)=> {
                //继续监听
                Accept();
                receive(x.Result);
            });
        }


        private void receive(Socket serverSocket)
        {
            Task.Run(() =>
            {
                try
                {
                    string recStr = "";
                    byte[] recByte = new byte[4096];
                    int bytes = serverSocket.Receive(recByte, recByte.Length, 0);
                    recStr += Encoding.ASCII.GetString(recByte, 0, bytes);
                    AddMessageBoxAync(serverSocket.RemoteEndPoint.ToString() + ": " + recStr);
                }
                catch (Exception ex)
                {
                    var des = serverSocket.RemoteEndPoint.ToString();
                    serverSocket.Shutdown(SocketShutdown.Both);
                    serverSocket.Close();
                    AddMessageBoxAync(des+": disConnect");
                    //throw;
                }
                
            }).ContinueWith((x)=> {
                if (serverSocket.Connected)
                {
                    receive(serverSocket);
                }
            });
        }
         

        /// <summary>
        /// 显示信息
        /// </summary>
        /// <param name="message"></param>
        private void AddMessageBoxAync(string message)
        {
            messageBox.Invoke((Action)(()=> { AddMessageBox(message); }) );
        }

        /// <summary>
        /// 显示信息
        /// </summary>
        /// <param name="message"></param>
        private void AddMessageBox(string message)
        {
            messageBox.AppendText(message + "\n");
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
           // serverSocket.Close();
            sSocket.Close();
        }
    }
}
